/*
 *  Copyright 2009 Lucas Nazário dos Santos
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package net.sourceforge.retriever.filter;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import net.sourceforge.retriever.fetcher.Resource;

/**
 * Class used to filter URLs using regular expressions.
 */
public class URLRegexFilter implements Filter {


	private Map<String, Boolean> regexes = new HashMap<String, Boolean>();

	/**
	 * Adds a regular expression to be used in the filtering process.
	 * 
	 * The URL that pass by the filter must match one of the added regular
	 * expressions to be accepted.
	 * 
	 * @param regex Regular expression to be used during the filtering process.
	 */
	public void addRegex(final String regex) {
		this.addRegex(regex, true);
	}

	/**
	 * Adds a regular expression to be used in the filtering process.
	 * 
	 * If the boolean argument is true, then URLs matching the regex will be
	 * accepted, otherwise the URLs will be discarded.
	 * 
	 * @param regex Regular expression to be used in the filtering process.
	 * @param ifMatchAccept decide whether the URL that matches the regex
	 * 		  must be discard or not.
	 */
	public void addRegex(final String regex, final boolean ifMatchAccept) {
		this.regexes.put(regex, ifMatchAccept);
	}

	/**
	 * Filter a resource before the fetching process, when it's only a URL.
	 * 
	 * @param url The URL used in the filter process.
	 * @return True if the URL was accepted and won't be filtered and false otherwise.
	 */
	public boolean acceptBeforeFetch(final String url) {
		if (this.regexes.isEmpty()) return true;
		final Set<String> regexes = this.regexes.keySet();
		boolean result = false;
		for (String regex : regexes) {
			if (url.matches(regex)) {
				if (this.regexes.get(regex)) {
					result = true;
				} else {
					return false;
				}
			}
		}
		return result;
	}

	/**
	 * Always return true because the resource has already gone through the
	 * <code>acceptBeforeFetch(String)</code> method.
	 */
	public boolean acceptAfterFetch(final Resource resource) {
		return this.acceptBeforeFetch(resource.getURL().toExternalForm());
	}
}